﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XfTechOAWeb.Data;
using XfTechOAWeb.IService;
using XfTechOAWeb.Models;
using AutoMapper;
using XfTechOAWeb.Dtos.MyMessages;
using XfTechOAWeb.EFCore;
using MD5Hash;
using static CSRedis.Internal.Resp3Helper;
using System.Reflection;
using System.Data;
using XfTechOAWeb.Data.Base;
using Microsoft.AspNetCore.SignalR;
using XfTechOAWeb.Service.Hubs;
using XfTechOAWeb.Dtos;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;

namespace XfTechOAWeb.Service
{
    public class MyMessageService : IMyMessageService
    {
        private readonly IRepository<MyMessage> _messageRepository;
        private readonly IMapper _mapper;
        private readonly IRepository<Notice> _noticeRepository;
        //HttpContext访问
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="iMessage"></param>
        public MyMessageService(IMapper mapper,
            IRepository<MyMessage> messageRepository,
            IRepository<Notice> noticeRepository,
            IHttpContextAccessor httpContextAccessor)
        {
            _messageRepository = messageRepository;
            _mapper = mapper;
            _noticeRepository = noticeRepository;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 修改成已读
        /// </summary>
        /// <param name="opt"></param>
        /// <returns></returns>
        public int UpdateStatus(int id, int status)
        {
            string sql = $"update MyMessage set MessageState={status} where MId = {id}";
            return _messageRepository.ExecuteFromSql(sql);
        }

        /// <summary>
        /// 获取id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public MyMessage GetMessageId(int id)
        {
            return _messageRepository.GetById(id);
        }

        /// <summary>
        /// 获取为未读数量
        /// </summary>
        /// <returns></returns>
        public int GetUnReadCount()
        {
            //获取当前用户id
            int currentUserId = Convert.ToInt32(_httpContextAccessor.HttpContext.User.FindFirst(x => x.Type == ClaimTypes.NameIdentifier).Value ?? "0");

            if (AddNewMessage(currentUserId) < 0) //添加报错则返回-1
            {
                return -1;
            }

            //获取当前用户信息表里未读的消息数量
            int count = _messageRepository.Table.Count(x => x.UserId == currentUserId && x.MessageState == 0);

            return count;
        }

        /// <summary>
        /// 分页显示(不包括假删的数据)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PageResponseModel<MyMessageListDto> GetMessageByPage(MyMessagePageDto input)
        {
            //获取当前用户id
            int currentUserId = Convert.ToInt32(_httpContextAccessor.HttpContext.User.FindFirst(x => x.Type == ClaimTypes.NameIdentifier).Value ?? "0");
            //获取最新的系统公告，插入到我的消息表里
            AddNewMessage(currentUserId);

            //查询用户信息列表
            var query = from m in _messageRepository.Table
                        join n in _noticeRepository.Table on m.NoticeId equals n.NoticeId
                        where m.UserId == currentUserId &&
                          (string.IsNullOrEmpty(input.Content) || n.NoticeTitle.Contains(input.Content)) &&
                          (input.Status == null || m.MessageState == input.Status)
                        orderby m.MessageDate descending
                        select new MyMessageListDto
                        {
                            CreatedUser = n.CreatedUser,
                            MessageDate = m.MessageDate,
                            NoticeId = n.NoticeId,
                            MId = m.MId,
                            MessageState = m.MessageState,
                            NoticeTitle = n.NoticeTitle,
                            NoticeContent = n.NoticeContent
                        };

            PageResponseModel<MyMessageListDto> page = new PageResponseModel<MyMessageListDto>()
            {
                TotalCount = query.Count(),
                PageList = query.Skip((input.PageIndex - 1) * input.PageSize)
                            .Take(input.PageSize)
                            .ToList()
            };
            return page;
        }


        private int AddNewMessage(int userId)
        {
            //获取当前用户信息表里最大的消息时间
            DateTime lastMessageDate = _messageRepository.Table
                                                         .Where(x => x.UserId == userId)
                                                         .OrderByDescending(x => x.MessageDate)
                                                         .Select(s => s.MessageDate)
                                                         .FirstOrDefault();

            //获取所有最新消息
            List<Notice> noticeList = _noticeRepository.Table
                                        .Where(n => lastMessageDate.Equals(default(DateTime))
                                                 || n.CreatedTime > lastMessageDate)
                                        .ToList();

            foreach (var item in noticeList)
            {
                MyMessage myMessage = new MyMessage
                {
                    MessageState = 0,                //消息状态为未读
                    NoticeId = item.NoticeId,
                    UserId = userId,
                    MessageDate = item.CreatedTime,  //消息创建时间
                    MessageReadDate = null           //消息已读时间
                };
                _messageRepository.Insert(myMessage);
            }

            return _messageRepository.SaveChanges();
        }
    }
}
